package middleware

import (
	"blog_go/pkg/helper/jwt"
	"encoding/base64"
	"fmt"
	"net/http"
	"strings"

	"github.com/gin-gonic/gin"
)

// 中间件,认证token合法性
func JwtAuthMiddleware(j *jwt.JWT) gin.HandlerFunc {
	return func(c *gin.Context) {
		authHandler := c.Request.Header.Get("authorization")
		if authHandler == "" {
			c.JSON(http.StatusOK, gin.H{"code": 2003, "message": "请求头部auth为空", "data": "{}"})
			c.Abort()
			return
		}

		// 前两部门可以直接解析出来
		jwt := strings.Split(authHandler, ".")
		cnt := 0
		for _, val := range jwt {
			cnt++
			if cnt == 3 {
				break
			}
			msg, _ := base64.StdEncoding.DecodeString(val)
			fmt.Println("val ->", string(msg))
		}

		// 我们使用之前定义好的解析JWT的函数来解析它,并且在内部解析时判断了token是否过期
		claims, err := j.ParseToken(authHandler)
		if err != nil {
			fmt.Println("err = ", err.Error())
			c.JSON(http.StatusOK, gin.H{
				"code":    2005,
				"message": "无效的accessToken",
				"data":    "{}",
			})
			c.Abort()
			return
		}

		if claims.TokenType != "access" {
			c.JSON(http.StatusUnauthorized, gin.H{
				"code":    2006,
				"message": "Token类型错误",
				"data":    "{}",
			})
			c.Abort()
			return
		}

		if (strings.Contains(c.FullPath(), "/user/") && claims.UserType != 1) ||
			(strings.Contains(c.FullPath(), "/admin/") && claims.UserType != 0) ||
			(strings.Contains(c.FullPath(), "/currency/") && !(claims.UserType == 0 || claims.UserType == 1)) {
			c.JSON(http.StatusForbidden, gin.H{
				"code":    2004,
				"message": "Token不匹配请求的接口",
				"data":    "{}",
			})
			c.Abort()
			return
		}

		// 将当前请求的claims信息保存到请求的上下文c上
		c.Set("claims", claims)
		c.Next() // 后续的处理函数可以用过c.Get("claims")来获取当前请求的用户信息
	}
}
